$(function(){
	var $tabList=$("#tab_list"),$pagebar=$("#pagebar ul"),$pageInfo=$("#page_info"),
		pageNo=1,pageSize=10,count=0;//初始值
	/**---------------封装分页方法,count:总条目数,pageNo:当前页---------------*/
	function pageit(count){
		$pagebar.empty();
		//首页和上一页
		if(pageNo==1){
			$pagebar.append("<li id='start_page' class='disabled'><a href='javascript:void(0);'>首页</a></li>");
			$pagebar.append("<li id='prev_page'  class='disabled'><a href='javascript:void(0);'>上一页</a></li>");
		}else{
			$pagebar.append("<li id='start_page' pn=1><a href='javascript:void(0);'>首页</a></li>");
			$pagebar.append("<li id='prev_page' pn="+(pageNo-1)+"><a href='javascript:void(0);'>上一页</a></li>");
		}
		var tmp=parseInt(count/10);
		var page_size=count%10==0?(tmp):(tmp+1);//总页数
		//中间数字页
		if(page_size<=5){
			//如果小于5页,则全部显示
			for(var i = 0; i <page_size; i++) {
				if(i==pageNo-1){
					$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				}else{
					$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				}
			}
		}else{
			//如果总页数大于5页,显示当前页和前后各两页以及两个...符号
			if(pageNo<3){
				for(var i = 0; i <5; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
				$pagebar.append("<li class='disabled'><a href='javascript:void(0);'>...</a></li>");
			}else if(pageNo>page_size-2){
				$pagebar.append("<li class='disabled'><a href='javascript:void(0);'>...</a></li>");
				for(var i = page_size-5; i <page_size; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
			}else{
				for (var i = pageNo-3; i <pageNo+2; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(pageNo)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
			}
		}
		//下一页和末页
		if(page_size==0||pageNo==page_size){
			$pagebar.append("<li id='next_page' class='disabled'><a href='javascript:void(0);'>下一页</a></li>");
			$pagebar.append("<li id='end_page' class='disabled'><a href='javascript:void(0);'>末页</a></li>");
		}else{
			$pagebar.append("<li id='next_page' pn="+(pageNo+1)+"><a href='javascript:void(0);'>下一页</a></li>");
			$pagebar.append("<li id='end_page' pn="+page_size+"><a href='javascript:void(0);'>末页</a></li>");
		}
		
		//绑定事件
		$pagebar.find("li").not(".disabled").on("click",function(){
			pageNo=parseInt($(this).attr("pn"));//更新当前页码
			reloadList();
		});
		//分页信息条
		$pageInfo.find("span").each(function(i,k){
			if(i==0){
				if(page_size==0){
					$(k).html(0);
				}else{
					$(k).html((pageNo-1)*10+1);
				}
			}else if(i==1){
				$(k).html(count>pageNo*10?pageNo*10:count);
			}else{
				$(k).html(count);
			}
		});
	}
	/**------------------加载列表---------------------*/
	var noRecord= "<font style='color:red;font-weight:bold;font-size:13px;'>无</font>";
	var params={"pageNo":1,"pageSize":pageSize};
	var authStatus = {0:"认证中",1:"<font style='color:green;font-weight:bold;font-size:13px;'>已认证</font>",2:"<font style='color:red;font-weight:bold;font-size:13px;'>认证失败</font>"};
	var delStatus = {0:"<font style='color:green;font-weight:bold;font-size:13px;'>未删除</font> ",1:" <font style='color:red;font-weight:bold;font-size:13px;'>删除</font>"};
	function reloadList(){
		params.pageNo=pageNo;
		params.pageSize=pageSize;
		$.get(serverURL+"view/course/getList",params,function(data){
			try {
				if(data.code==0){
					data=data.data;
					$tabList.find("tbody").empty();
					count=data.pagination.totalCount;
					if(count>0){
						var html="";
						$.each(data.list,function(i,k){
							html+="<tr>" +
							"<td id='pkc'><input type='checkbox' id='"+k.courseId+"' class='checkbox' col='"+i+"' ></td>" +
							"<td>"+((pageNo-1)*10+i+1)+"</td>" +
							"<td>"+(k.title?k.title:noRecord)+"</td>"+ 
							"<td>"+(k.uploadTime?k.uploadTime:noRecord)+"</td>"+ 
							"<td>"+(k.downloadCount?k.downloadCount:noRecord)+"</td>"+ 
							"<td>"+(k.collectionCount?k.collectionCount:noRecord)+"</td>"+ 
							"<td>"+k.commentCount+"</td>"+ 
							"<td>"+k.visitCount+"</td>"+ 
							"<td>"+authStatus[k.authStatus]+"</td>"+ 
							"<td>"+delStatus[k.deleteStatus]+"</td>"+ 
							"<td><a type='button' class='btn btn-primary' href='course/addChapter.htm?courseId="+k.courseId+"' title='增加章节'>增加章节</a>&nbsp;" +
									"<a type='button' class='btn btn-primary' href='course/addVideo.htm?courseId="+k.courseId+"' title='增加视频'>增加视频</a></td>"+ 
							"</tr>";
						});
						$tabList.find("tbody").append(html);
//						$(".tools button").removeAttr("disabled");
					}else{
						$tabList.find("tbody").append("<tr><td colspan="+$("thead th").length+">无数据</td></tr>");
//						$(".tools button").not(".btn-default").attr("disabled","disabled");
					}
					pageit(count);//重绘工具栏
				}else if(data.code!=-1){
					alert("数据加载出错，请稍后重试");
				}
			} catch (e) {
				alert("数据加载出错，请稍后重试");
			}
		});
	}
	reloadList();
	//全选与取消全选
	$("#pkall").change(function(){
		if($(this).prop("checked")){
			$tabList.find("#pkc :checkbox").prop("checked",true);
		}else{
			$tabList.find("#pkc :checkbox").prop("checked",false);
		}
	});
	//获取选中的行
	function getSelectedCols(){
		return $tabList.find("#pkc :checkbox").filter(":checked");
	}

	/**---------------查询-----------------*/
	$("#btn_search").click(function(){
		params.nickName=$("#search_nickName").val();
		params.phone=$("#search_phone").val();
		pageNo=1;
		reloadList();
		return false;
	});
	/**---------------重置-----------------*/
	$("#btn_reset").click(function(){
		$("#form_search").get(0).reset();
		pageNo=1;
		reloadList();
		return false; 
	});
    
    
	var $formUpload=$("#form_upload");
	var imgReg=/^.+\.(jpg|png|bmp|gif)$/;

	$formUpload.find("[name=file]").change(function(){
		$formUpload.ajaxSubmit({  
			dataType:'json',
			resetForm:true,
	        success:function(data){
	        	if(data.code==0){
	        		$("#bigPic_Show").attr("src",data.data.url).parent().attr("href",data.data.url);
	        		$formUpload.find("[name=previewPath]").val(data.data.url);
	        	}else{
	        		alert("文件上传失败，请重试");
	        		$formUpload.get(0).reset();
	        	}
	        } 
		});
	});
	
	var $formAdd = $("#form_add");
	/** ************添加课程*************** */
    $("#btn_add").click(function(){
    	$("#modal_add").modal("show");
    	addCategory($formAdd);
    	addPlan();
        $("#tags").tagsInput({
            width: 'auto',
            onChange: function (elem, elem_tags) {
            },
        });
    });
    
	function checkAddForm(){
		if($formUpload.find("[name=previewPath]").val()==""){
			warnInput($("[name=file]"));
			return false;
		}
		if($("[name=title]").val() == ""){
			warnInput($("[name=title]"));
			return false;
		}
		if($("[name=teacher]").val() == 0){
			warnInput($("[name=teacher]"));
			return false;
		}	
		if($("[name=top]").val() == 0){
			warnInput($("[name=top]"));
			return false;
		}
		if($("[name=second]").val() == 0){
			warnInput($("[name=second]"));
			return false;
		}
		if($("[name=detail]").val() == 0){
			warnInput($("[name=detail]"));
			return false;
		}
		if($("[name=add_startTime]").val() == ""){
			warnInput($("[name=add_startTime]"));
			return false;
		}
		if($("[name=add_endTime]").val() == ""){
			warnInput($("[name=add_endTime]"));
			return false;
		}
		if($("[name=add_endTime]").val() <=$("[name=add_startTime]").val() ){
			alert("结束时间不能早于开始时间");
			return false;
		}
		if($("[name=hierId]").val() == 0){
			warnInput($("[name=hierId]"));
			return false;
		}
		
		if($("[name=grade]").val() == 0){
			warnInput($("[name=grade]"));
			return false;
		}
		if($("[name=tags]").val()  == ""){
			alert("请输入标签");
			return false;
		}
		if( $("textarea[name='content1']").val()== ""){
			alert("请输入简介");
			return false;
		}
		return true;
	}
	
		/*** 提交课程*/
	 $("#btn_confirm_add").click(function() {
		if (checkAddForm()) {
				previewPath = $formUpload.find("[name=previewPath]").val();
				title = $formAdd.find($("[name=title]")).val();
				tcId =$formAdd.find($("[name=top]")).val();
				scId =$formAdd.find($("[name=second]")).val();
				thirdId = $formAdd.find($("[name=detail]")).val();
				hierId = $formAdd.find($("[name=hierId]")).val();
				grade = $formAdd.find($("[name=grade]")).val();
				teacherId = $formAdd.find($("[name=teacher]")).val();
				endTime = $("[name=add_endTime]").val()；
				startTime = $("[name=add_startTime]").val();

				introduction = $("textarea[name='content1']").val();
				
				var tag = $("#tags").val();
				$.ajax({ // 此处用同步处理，避免出现val()比reload早的问题
					url : serverURL + "view/course/addBatch?tags="+tag,
					type : "post",
					async : false,
					success : function(data) {
						if (data.code == 0) {
							$.post(serverURL + "view/course/add", {"authStatus":'1',"grade":grade,"hierId":hierId,"userId":teacherId,"title" : title,"previewPath" : previewPath,"labelIds" : data.data,"tcId" : tcId,"scId" : scId,"thirdId":thirdId,"introduction":introduction,"endTime":endTime,"startTime":startTime}, function(data) {
								if (data.code == 0) {
									alert("资料添加成功");
									$("#modal_add").modal("hide");
									$("#form_add").get(0).reset();
									pageNo=1;
									reloadList();
								} else if (data.code != -1) {
									alert("添加失败,请稍后重试");
								}
							});
		
						} else if (data.code != -1) {
							alert("数据添加失败");
						}
					}
				});		
				
			}
	})

	 /**添加规划体系* */
	function addPlan(){
		$.get("view/plan/getList",{"all":true}, function(data) {
			$("#form_add").find("[name=hierId]").empty().html("<option value='0' selected='selected'>请选择规划体系...</option>");
			$.each(data.data.list,function(i,k){
			   
				$("#form_add").find("[name=hierId]").append("<option value='" + k.hierId + "'>" + k.hierName+ "</option>");
			});
		}, "json");
	} 
	 
	/** ***********添加分类********************* */
	function addCategory(object) {
			// 一级分类选择
			var $second = object.find("[name=second]"), 
			$top = object.find("[name=top]");
			$detail = object.find("[name=detail]"), 
	
			$.get("view/video/category/getTopCategory", function(data) {
				$.each(data.data, function(i, obj) {
					$top.append("<option value='" + obj.tcId + "'>" + obj.tcName+ "</option>");
				});
			}, "json");
			/*--------------修改的一、二、三级二级联动处理----------------*/
			$top.change(function() {
					districtEdit.clearDetail();
					districtEdit.reloadSecond($(this).val());
				});
		
				$second.change(function() {
					districtEdit.reloadDetail($(this).val());
				});
		
				var districtEdit = {
					clearSecond : function() {
						$second.find("option[value!=0]").remove();
					},
					clearDetail : function() {
						$detail.find("option[value!=0]").remove();
					},
					reloadSecond : function(tcId) {
						districtEdit.clearSecond();
						if (tcId != 0) {
							$.ajax({ // 此处用同步处理，避免出现val()比reload早的问题
								url : serverURL + "view/video/category/getSecondaryCategory?"+ "tcId=" + tcId,
								type : "get",
								async : false,
								success : function(data) {
									if (data.code == 0) {
										var html = "";
										$.each(data.data, function(i, k) {
											html += "<option value='" + k.scId +"'>"+ k.scName + "</option>";
										});
										$second.append(html);
									} else if (data.code != -1) {
										alert("二级分类数据加载失败");
									}
								}
							});
						}
					},
					reloadDetail : function(scId) {
						districtEdit.clearDetail();
						if (scId != 0) {
							$.ajax({
								url : serverURL + "view/video/category/getDetailCategory?"+ "scId=" + scId+"&dcTypeId=0",
								type : "get",
								async : false,
								success : function(data) {
									if (data.code == 0) {
										$.each(data.data, function(i, k) {
												$detail.append("<option value='" + k.dcId + "'>"+ k.dcName + "</option>");											
										});
									} else if (data.code != -1) {
										alert("三级分类数据加载失败");
									}
								}
							});
						}
					}
			
				};		
		}
	 
	/***************查看详情********************/
//    $("#btn_scan").click(function() {
		// 获取选中的行
//		var $curCol = $tabList.find("#pkc :checkbox").filter(":checked");
//		if ($curCol.length != 1) {
//			alert("请选择一条记录预览");
//			return;
//		}
//		var id = $curCol[0].id;
//		alert(id);
//		window.location.href="thesis/tiaozhuan.htm?thesisId="+id;
		//$("#modal_scan").modal("show");
//	});	
	
	/**************删除************/
	$("#btn_del").click(function(){
		var $curCol = $tabList.find("#pkc :checkbox").filter(":checked");
		if ($curCol.length == 0) {
			alert("请至少选择一条记录删除");
			return;
		}
		var ids = "";
		$.each($curCol, function(i, k) {
			ids += $curCol[i].id + ",";
		})
		ids = ids.substring(0, ids.length - 1);
		$.get(serverURL + "view/course/delCourse", {"courseIds" : ids}, function(data) {
			if (data.code == 0) {
				alert("删除成功");
				pageNo=1;
				reloadList();
			} else if (data.code != -1) {
				alert("删除失败,请稍后重试");
			}
		});
		
	});
	
});